import { debounce } from 'lodash'
import { onMounted, onUnmounted } from 'vue'

export function useKeyUpListener(
  onClickPre: () => void,
  onClickNext: () => void,
  onToggleShowAnswer: () => void,
) {
  const onClickLeft = debounce(onClickPre, 500, {
    trailing: false,
    leading: true,
  })
  const onClickRight = debounce(onClickNext, 500, {
    trailing: false,
    leading: true,
  })
  function onKeyUp(e: KeyboardEvent) {
    if (e.key === 'ArrowLeft') onClickLeft()
    if (e.key === 'ArrowRight') onClickRight()
    if (e.key === 'ArrowUp' || e.key === 'ArrowDown') onToggleShowAnswer()
  }

  onMounted(() => document.addEventListener('keyup', onKeyUp))
  onUnmounted(() => document.removeEventListener('keyup', onKeyUp))
}
